<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Session\Store;
use Illuminate\Session\ArraySessionHandler;
use Illuminate\Session\SessionManager;
use App\Services\WordPressAssetService;

/**
 * WordPress兼容的Session服务提供者
 * 使用内存存储，避免数据库操作
 */
class NoSessionServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        // 注册使用ArraySessionHandler的session store
        $this->app->singleton('session.store', function ($app) {
            $handler = new ArraySessionHandler(0);
            $store = new Store('wordpress', $handler);

            // 生成Session ID
            $userId = 0;
            if (function_exists('get_current_user_id')) {
                $userId = get_current_user_id();
            }

            $sessionId = $userId > 0
                ? 'wp_user_' . $userId . '_' . uniqid()
                : 'wp_guest_' . uniqid() . '_' . time();

            $store->setId($sessionId);
            $store->start();

            // 添加WordPress用户信息到session
            if ($userId > 0) {
                $store->put('wp_user_id', $userId);

                if (function_exists('wp_get_current_user')) {
                    $user = wp_get_current_user();
                    $store->put('wp_user_login', $user->user_login ?? '');
                    $store->put('wp_user_roles', $user->roles ?? []);
                    $store->put('wp_user_display_name', $user->display_name ?? '');
                }
            }

            return $store;
        });

        // 注册session管理器
        $this->app->singleton('session', function ($app) {
            $manager = new SessionManager($app);

            // 设置默认驱动为我们的WordPress兼容实现
            $manager->extend('wordpress', function ($app) {
                return $app['session.store'];
            });

            return $manager;
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // 配置WordPress插件环境的资源URL
        WordPressAssetService::configureAssetUrl();

        // 设置session驱动为我们的WordPress兼容实现
        config([
            'session.driver' => 'wordpress',
            'session.lifetime' => 120,
            'session.expire_on_close' => false,
            'session.encrypt' => false,
            'session.files' => storage_path('framework/sessions'),
            'session.connection' => null,
            'session.table' => 'sessions',
            'session.store' => null,
            'session.lottery' => [2, 100],
            'session.cookie' => env('SESSION_COOKIE', 'wp_lara_press_session'),
            'session.path' => '/',
            'session.domain' => env('SESSION_DOMAIN', null),
            'session.secure' => env('SESSION_SECURE_COOKIE', false),
            'session.http_only' => true,
            'session.same_site' => 'lax',
        ]);
    }
}
